import React, { PureComponent, Fragment } from 'react';
import { routerRedux, Route } from 'dva/router';
import { connect } from 'dva';
import {
  Form,
  Select,
  Input,
  Card,
  message,
  Checkbox,
  Tree,
  Button,
  Row,
  Col,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Link } from 'react-router-dom';

import querystring from 'querystring';
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;
const TreeNode = Tree.TreeNode;

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

@connect(({ system }) => ({
  system,
}))
@Form.create()
export default class TaskSigned extends PureComponent {
  state = {
    id: '',
    nodeId: '',
    systemAssignedList: null,
    modalVisible: false,
    checkboxOption: [],
    loanFlag: true,
    loanValue: '',
    showSelect1: false,
    showSelect2: false,
    showSelect3: false,
    getRuleTreeFlag: false,
    systemNodeAssignRoleList: null
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      id: params.id,
      nodeId: params.nodeId,
    });
    dispatch({
      type: 'system/getRoluesTree',
      payload: {
        nodeAssignId: params.id,
      },
    });
    dispatch({
      type: 'system/getPersonnes',
      payload: {
        nodeId: params.nodeId
      },
      callback: () => {
        const { system: { systemAssignedList } } = this.props;
        systemAssignedList &&
          this.setState({
            systemAssignedList,
          })
        // console.log("systemAssignedList", systemAssignedList)
      }
    });
  }

  handleSelectAssignedList = (data) => {
    // console.log("handleSelectAssignedList", data[0].assignerId)
    const options = [];
    data.map(item => {
      options.push(<Option value={item.assignerId} key={item.assignerId}>{item.assigner}</Option>);
    });
    return options;
  }

  handleChange = (value, record) => {
    const treeData = record

    switch (record.level) {
      case 0:
        this.state.systemNodeAssignRoleList &&
          this.state.systemNodeAssignRoleList.map(item => {
            if (treeData.nid == item.nid) {
              item.operator = value
            }
          })
        break;

      case 1:
        this.state.systemNodeAssignRoleList &&
          this.state.systemNodeAssignRoleList.map(item => {
            item.children = item.children.map(item1 => {
              if (treeData.nid == item1.nid) {
                item1.operator = value
              }
              return item1
            })
          })
        break;
      case 2:
        this.state.systemNodeAssignRoleList &&
          this.state.systemNodeAssignRoleList.map(item => {
            item.children = item.children.map(item1 => {
              item1.children = item1.children.map(option => {
                if (treeData.nid == option.nid) {
                  option.operator = value
                }
                return option
              });
              return item1
            })
          })
        break;
    }
  };

  renderTreeNodeChild = record => {
    // const level = record.level;
    // console.log("renderTreeNodeChild", record)
    return (
      <span>
        {record.children.length == 0 && (
          <Select
            placeholder="选择人"
            size="small"
            defaultValue={record && record.operator}
            style={{ width: 150, marginLeft: '10px' }}
            onChange={(value) => this.handleChange(value, record)}
          >
            {this.state.systemAssignedList && this.handleSelectAssignedList(this.state.systemAssignedList)}
          </Select>
        )}
      </span>
    );
  };

  //确定
  handleChangeRules = () => {
    let branchId = null;
    let productId = null;
    let priceTo = null;

    if (this.state.showSelect1) {
      branchId = 1
      this.setState({ getRuleTreeFlag: true })
    }
    if (this.state.showSelect2) {
      productId = 1
      this.setState({ getRuleTreeFlag: true })
    }
    if (this.state.showSelect3) {
      if (this.state.loanValue) {
        priceTo = this.state.loanValue
        this.setState({ getRuleTreeFlag: true })
      } else {
        message.warning("请填写分割价格")
        return;
      }
    }
    if (!this.state.showSelect1 && !this.state.showSelect2 && !this.state.showSelect3) {
      message.warning("请先选择")
      return;
    }
    if (branchId == 1 || productId == 1 || priceTo != null) {
      const { dispatch } = this.props;
      dispatch({
        type: 'system/getNodeAssignRole',
        payload: {
          branchId,
          productId,
          priceTo,
        },
        callback: () => {
          const { system: { systemNodeAssignRoleList } } = this.props;
          this.setState({ systemNodeAssignRoleList, })
        }
      });
    }
  }

  //提交
  handleSubmitRules = () => {
    let branchId = null;
    let productId = null;
    let priceTo = null;
    if (this.state.showSelect1) {
      branchId = 1
    }
    if (this.state.showSelect2) {
      productId = 1
    }
    if (this.state.showSelect3) {
      if (this.state.loanValue) {
        priceTo = this.state.loanValue
      } else {
        message.warning("请填写分割价格")
        return;
      }
    }
    if (branchId == 1 || productId == 1 || priceTo != null) {
      const { dispatch } = this.props;
      dispatch({
        type: 'system/saveTree',
        payload: {
          branchId,
          productId,
          priceTo,
          nodeAssignId: this.state.id,
          datas: [...this.state.systemNodeAssignRoleList]
        },
        callback: () => {
          const { system: { systemResult } } = this.props;
          if (systemResult.code == 200) {
            message.success("提交成功")
            dispatch(routerRedux.push(`/search/allocation-rules`));
          } else {
            message.success(systemResult.message)
          }
        }
      });
    }
  }

  renderTreeNodesChildren = record => {
    return (
      <TreeNode
        title={
          <div>
            {record.name}
            {this.renderTreeNodeChild(record)}
          </div>
        }
        value={record.nid}
        key={record.nid}
        dataRef={record}
      >
        {record.children &&
          record.children.length > 0 &&
          record.children.map(item => {
            return this.renderTreeNodesChildren(item);
          })}
      </TreeNode>
    );
  };

  handleLoanChangeValue = e => {
    this.setState({
      loanValue: e.target.value,
    });
  };

  render() {
    const { system: { systemNodeAssignRoleList, userLoading, systemLoading, systemRoluesTreeList } } = this.props;
    return (
      <PageHeaderLayout title="规则制定">
        {/* {JSON.stringify(systemRoluesTreeList)} */}
        <Card bordered={false} title="规则选择" >
          <Row>
            <Col span={8}>
              <Checkbox
                defaultChecked={false}
                label="组织"
                onChange={e => {
                  this.setState({
                    showSelect1: e.target.checked,
                  });
                }}
              />
              组织
              <Checkbox
                defaultChecked={false}
                label="组织"
                onChange={e => {
                  this.setState({
                    showSelect2: e.target.checked,
                  });
                }}
              />
              产品
              <Checkbox
                defaultChecked={false}
                label="组织"
                onChange={e => {
                  this.setState({
                    showSelect3: e.target.checked,
                    loanValue: null
                  });
                }}
              />
              贷款额
            </Col>
            <Col span={6}>
              <Input
                placeholder="请输入分割价格"
                value={this.state.loanValue}
                onChange={this.handleLoanChangeValue}
                disabled={!this.state.showSelect3}
              />
            </Col>
            <Col span={6}>
              <Button type="primary" style={{ marginLeft: '20px' }} onClick={this.handleChangeRules}>确定</Button>
            </Col>
          </Row>
          <Row>
            <Col>

              <Tree
                key={`tree${this.state.showSelect1}${this.state.showSelect2}${
                  this.state.showSelect3
                  }`}
                showLine
                defaultExpandAll={true}
                autoExpandParent={true}
                defaultExpandParent={true}
                onSelect={this.handleSelect}
              >
                {this.state.getRuleTreeFlag ?
                  systemNodeAssignRoleList &&
                  systemNodeAssignRoleList.map(item => {
                    return this.renderTreeNodesChildren(item);
                  })
                  :
                  systemRoluesTreeList &&
                  systemRoluesTreeList.map(item => {
                    return this.renderTreeNodesChildren(item);
                  })
                }

              </Tree>
            </Col>
          </Row>
          {
            this.state.getRuleTreeFlag ?
              <Row style={{ marginTop: '40px' }}>
                <Col span={2}>
                  <Button type="primary" style={{ marginLeft: '20px' }} onClick={this.handleSubmitRules} loading={userLoading}>提交</Button>
                </Col>
                <Col span={2}>
                  <Button style={{ marginLeft: '20px' }}>
                    <Link to='/search/allocation-rules'>
                      返回
                    </Link>
                  </Button>
                </Col>
              </Row>
              : null
          }

        </Card>
      </PageHeaderLayout>
    );
  }
}
